//
//  mttBackgroundImage.m
//  mtt
//
//  Created by Gerfried Mikusch on 10.08.10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "mttBackgroundImage.h"
#import "UIImage-Alpha.h"
#import "mttBgImgMenuViewController.h"

@implementation mttBackgroundImage

@synthesize longPressRecognizer, panRecognizer, rotationRecognizer, pinchRecognizer, alphaMask, alphaMaskWidth, menuPopover, delegate;


BOOL editMode;
mttBgImgMenuViewController *menuView;


#pragma mark -
#pragma mark Alpha Mask


- (NSData *)alphaMask
{
    if (alphaMask == nil){
        
        self.alphaMask = [self.image alphaData];
        self.alphaMaskWidth = [self.image size].width;
        
    }
    return alphaMask;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event; 
{
	
    if ( (point.x > self.frame.size.width) || (point.y > self.frame.size.height) 
        || point.x < 0 || point.y < 0){
        return nil;
    }
    NSData *rawData = [self alphaMask];  // caching of alpha Mask
    if (rawData){
        NSUInteger index = point.x + (point.y * alphaMaskWidth);
        char *rawDataBytes = (char *)[rawData bytes];
        //NSLog(@"xy:%lf:%lf->%d", point.x, point.y, rawDataBytes[index]);        
        return (rawDataBytes[index] == 0) ? nil : self;
    }
    return self;
}


- (void)setImage:(UIImage *)image
{
    self.alphaMask = nil;
    [super setImage:image];
}



#pragma mark -
#pragma mark gesture recognizing


-(void)handleLongPress:(UILongPressGestureRecognizer *)recognizer {
	
	if (recognizer.state == UIGestureRecognizerStateBegan) {
		
		CGPoint hitPoint = [recognizer locationInView:self];
		menuView = [[mttBgImgMenuViewController alloc] initWithNibName:@"mttBgImgMenuViewController" bundle:[NSBundle mainBundle]];
		menuView.delegate = self;
		menuView.editSwitch.on = editMode;
		menuPopover = [[UIPopoverController alloc] initWithContentViewController:menuView];
		[menuPopover setPopoverContentSize:menuView.view.frame.size animated:YES];
		[menuPopover presentPopoverFromRect:CGRectMake(hitPoint.x, hitPoint.y, 10, 10) inView:self permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
		
	}
}


// Bewegt das Bild
-(void)handlePan:(UIPanGestureRecognizer *)recognizer {
		
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		CGPoint translation = [recognizer translationInView:self.superview];
		[self setCenter:CGPointMake(self.center.x + translation.x, self.center.y + translation.y)];
		[recognizer setTranslation:CGPointZero inView:self.superview];
	}
	
}

// Rotiert das Bild
- (void)handleRotation:(UIRotationGestureRecognizer *)recognizer {
	
    if ([recognizer state] == UIGestureRecognizerStateBegan || [recognizer state] == UIGestureRecognizerStateChanged) {
		self.transform = CGAffineTransformRotate(self.transform, [recognizer rotation]);
        [recognizer	setRotation:0];
    }
	
	
}

// Skaliert das Bild
- (void)handlePinch:(UIPinchGestureRecognizer *) recognizer {
	
	if (recognizer.state == UIGestureRecognizerStateBegan || recognizer.state == UIGestureRecognizerStateChanged) {
		self.transform = CGAffineTransformScale(self.transform, recognizer.scale, recognizer.scale);
		recognizer.scale = 1;
	}
}


- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    
	if (gestureRecognizer == self.pinchRecognizer ||
		gestureRecognizer == self.rotationRecognizer ||
		gestureRecognizer == self.panRecognizer ||
		otherGestureRecognizer == self.pinchRecognizer ||
		otherGestureRecognizer == self.rotationRecognizer ||
		otherGestureRecognizer == self.panRecognizer) {
		return YES;
	}
	return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
    return YES;
}

-(void)setGestureRecognizersEnabled:(BOOL)enabled {
	
	//LongTap soll immer gehen
	self.pinchRecognizer.enabled = enabled;
	self.rotationRecognizer.enabled = enabled;
	self.panRecognizer.enabled = enabled;
	
}

#pragma mark -
#pragma mark mttBgImgMenuViewController Delegate Methods

-(void)didRemoveBackground {
	
	[self removeFromSuperview];
	[[self menuPopover] dismissPopoverAnimated:YES];
	
	//sollte der Hintergrund während des editieren gelöscht werden, müssen alle Bilder wieder aktiviert werden.
	if (panRecognizer.enabled) {
		[delegate setImagesAlpha:1.0];
		[delegate setImagesInteraction:YES];
	}
}

-(void)didSwitchEditMode:(UISwitch *) sender {
	
	if (sender.on) {
		[delegate setImagesAlpha:0.0];
		[delegate bringViewToFront:self];
		[delegate bringOptionViewToFront];
		
	} else {
		[delegate setImagesAlpha:1.0];
		[delegate sendViewToBack:self];
	}
	
	[delegate setImagesInteraction:!sender.on];
	[self setGestureRecognizersEnabled:sender.on];
	[[self menuPopover] dismissPopoverAnimated:YES];
	editMode = sender.on;
	
}

-(BOOL)isEditMode {
	return editMode;
}



#pragma mark -
#pragma mark init & dealloc

- (id)initWithImage:(UIImage *)image {
	[super initWithImage:image];
	
	
	self.contentMode = UIViewContentModeScaleAspectFill;
	CGRect rect = self.frame;
	rect.size = CGSizeMake(1024, 768);
	self.frame = rect;
	
	
	[self setUserInteractionEnabled:YES];
	[self setMultipleTouchEnabled:YES];
	
	
	UIGestureRecognizer *recognizer;
	
	recognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
	[self addGestureRecognizer:recognizer];
	self.longPressRecognizer = (UILongPressGestureRecognizer *) recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
	[self addGestureRecognizer:recognizer];
	self.panRecognizer = (UIPanGestureRecognizer *)recognizer;
	self.panRecognizer.maximumNumberOfTouches = 2;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(handleRotation:)];
	[self addGestureRecognizer:recognizer];
	self.rotationRecognizer = (UIRotationGestureRecognizer *)recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	recognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(handlePinch:)];
	[self addGestureRecognizer:recognizer];
	self.pinchRecognizer = (UIPinchGestureRecognizer *)recognizer;
	recognizer.delegate = self;
	[recognizer release];
	
	//Kurze Animation des hintergrunds um darauf aufmerksam zu machen!
	CGContextRef context = UIGraphicsGetCurrentContext();
	[UIView beginAnimations:nil context:context];
	[UIView setAnimationDuration:0.2];
	
	self.transform = CGAffineTransformMakeScale(1.1, 1.1);
	self.transform = CGAffineTransformMakeScale(1.0, 1.0);
    
    [UIView commitAnimations];
	
	[self setGestureRecognizersEnabled:NO];
	editMode = NO;
	
	return self;
}

- (void) dealloc {
	
	[longPressRecognizer release];
	[panRecognizer release];
	[rotationRecognizer release];
	[pinchRecognizer release];
	[menuPopover release];
	[super dealloc];
	
}


@end
